import { applicationConfiguration } from '@/http/modules/api'
import { asyncRoutes, constantRoutes } from '@/router/index'

function hasPermission(grantedPolicies, route) {
  if (route.meta && route.meta.policy) {
    const policy = route.meta.policy
    return grantedPolicies[policy]
  } else {
    return true
  }
}

export function filterAsyncRoutes(routes, grantedPolicies) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(grantedPolicies, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, grantedPolicies)
      }

      if (route.meta && route.meta.policy === '') {
        if (tmp.children.length > 0) {
          res.push(tmp)
        }
      } else {
        res.push(tmp)
      }
    }
  })
  return res
}

const state = {
  abpConfig: null,
  policies: [],
  addRoutes: [],
  routes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ABPCONFIG: (state, abpConfig) => {
    state.abpConfig = abpConfig
    state.policies = abpConfig.auth.grantedPolicies
  }
}

const actions = {
  generateRoutes({ commit }, grantedPolicies) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, grantedPolicies)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  applicationConfiguration({ commit }) {
    return new Promise((resolve, reject) => {
      applicationConfiguration()
        .then(response => {
          commit('SET_ABPCONFIG', response)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
